import { login } from "@/api"; // 导入登录API函数

const state = {
  token: localStorage.getItem("token") || "", // 初始化时从本地存储读取
  userInfo: JSON.parse(localStorage.getItem("userInfo")) || null,
};

const mutations = {
  SET_TOKEN(state, token) {
    console.log("给state设置token@", state, token);
    state.token = token;
    // 持久化到本地存储
    localStorage.setItem("token", token);
  },
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo;
    localStorage.setItem("userInfo", JSON.stringify(userInfo));
  },
  // 清除Token和用户信息（用于退出登录）
  CLEAR_USER_DATA(state) {
    state.token = "";
    state.userInfo = null;
    localStorage.removeItem("token");
    localStorage.removeItem("userInfo");
  },
};

const actions = {
  // 登录动作
  Login({ commit }, loginForm) {
    return new Promise((resolve, reject) => {
      login(loginForm).then((res) => {
          if(res.code == 200){
          // 提交mutation来更新state
          commit("SET_TOKEN", res.data.token);
          commit("SET_USER_INFO", res.data.userInfo);
          resolve();
          }else{
            console.log('@@login',res)
            reject(res.message);
          }

        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // 退出登录动作
  Logout({ commit }) {
    commit("CLEAR_USER_DATA");
  },

  // 可选：应用启动时，尝试用本地token获取用户信息
  tryAutoLogin({ commit, state }) {
    if (state.token) {
      // 这里可以调用一个获取用户信息的API
      // api.getUserInfo().then(response => {
      //   commit('SET_USER_INFO', response.data.user);
      // });
      console.log(commit);
    }
  },
};

const getters = {
  isAuthenticated: (state) => !!state.token, // 便捷的计算属性，用于判断是否已登录
  userInfo: (state) => state.userInfo,
  token: (state) => state.token,
};

export default {
  namespaced: true, // 启用命名空间
  state,
  mutations,
  actions,
  getters,
};
